using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Columns;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraTreeList.Columns;
using WinformDevelopFrame.Core.Extend;
using WinformDevelopFrame.Core.Form;
using WinformDevelopFrame.Entity;
using WinformDevelopFrame.IServices;
using WinformDevelopFrame.Services;
using WinformDevelopFrame.Template;
using DevExpress.XtraEditors.Repository;
using WinformDevelopFrame.Common;

namespace  WinformDevelopFrame.UI
{
    public partial class Frmsysmenu : BaseForm
    {
        private ISqlSugarClient _sqlSugarClient;
        private IsysmenuService _sysmenuService;
        private ISysDataTableService _sysDataTableService;
        public  Frmsysmenu(ISqlSugarClient sqlSugarClient, IsysmenuService sysmenuService, ISysDataTableService sysDataTableService)
        {
            gridControl1.Enabled = false;
            _sqlSugarClient = sqlSugarClient;
            _sysmenuService = sysmenuService;
            _sysDataTableService = sysDataTableService;
            InitializeComponent();
            Init();
        }

        public override void Form_Load()
        {
            InitListCol();
        }
        /// <summary>
        /// 设置list lookupedit 列
        /// </summary>
        private void InitListCol()
        {
            
        }
        //设置不可编辑
        private void SetReadOnlyField()
        {
            ReadOnlyList.Add("Id");
            ReadOnlyList.Add("BId");
            ReadOnlyList.Add("CreateUserId");
            ReadOnlyList.Add("CreateTime");
            ReadOnlyList.Add("UpdateUserId");
            ReadOnlyList.Add("UpdateTime");
        }
        /// <summary>
        /// 设置数据 设置列名
        /// </summary>
        private void Init()
        {
            //fileds.Add("PId", "父ID");
            fileds.Add("MenuText", "菜单名称");
            fileds.Add("MenuCode", "菜单编码");
            fileds.Add("Icon", "菜单图标");
            fileds.Add("MenuType", "菜单类型");
            fileds.Add("MenuDll", "菜单地址");
            fileds.Add("IsExtendDevelop", "是否扩展开发");
            fileds.Add("MenuName", "菜单类名");
            fileds.Add("IsPublicFunction", "是否通用功能");
            fileds.Add("OrderNo", "排序");
            fileds.Add("ShowType", "显示方式");
            fileds.Add("CreateUserId", "创建人");
            fileds.Add("CreateTime", "创建时间");
            fileds.Add("UpdateUserId", "修改人");
            fileds.Add("UpdateTime", "修改时间");
            fileds.Add("Remark", "备注");
            SetReadOnlyField();
            PId.Properties.DataSource =
                _sqlSugarClient.Ado.GetDataTable(_sysDataTableService.QueryByClause(p => p.DataTableName.Equals("菜单-treelistLookupedit")).SQL);
            var menu = _sysmenuService.Query();
            foreach (var keyValuePair in fileds)
            {
                TreeListColumn column = new TreeListColumn();
                column.FieldName = keyValuePair.Key;
                column.Caption = keyValuePair.Value;
                column.Visible = true;
                treeList1.Columns.Add(column);
            }

            treeList1.KeyFieldName = "Id";
            treeList1.ParentFieldName = "PId";
            var m = _sysmenuService.QueryByClause(p => p.MenuCode.Equals(this.Name));
            //获取工具按钮
            var menus=_sysmenuService.QueryListByClause(p=>p.PId==m.Id).OrderBy(p=>p.OrderNo).ToList();
            menus.ForEach(p =>
            {
                btns.Add(new SimpleButton()
                {
                    Text = p.MenuText,
                    Name = p.MenuCode,
                    Image = Image.FromFile(Application.StartupPath+p.MenuIcon)
                });
            });

            CreateUserId.Properties.DataSource = _sqlSugarClient.Ado.GetDataTable(_sysDataTableService
                .QueryByClause(p => p.DataTableName.Equals("用户-lookupedit")).SQL);
            CreateUserId.Properties.DisplayMember = "用户名称";
            CreateUserId.Properties.ValueMember = "Id";
            UpdateUserId.Properties.DataSource = _sqlSugarClient.Ado.GetDataTable(_sysDataTableService
                .QueryByClause(p => p.DataTableName.Equals("用户-lookupedit")).SQL);
            UpdateUserId.Properties.DisplayMember = "用户名称";
            UpdateUserId.Properties.ValueMember = "Id";
            treeList1.Columns["CreateUserId"].ColumnEdit = new RepositoryItemLookUpEdit()
            {
                Name = "repositoryItemLookUpEditCreateUserId",
                DataSource = _sqlSugarClient.Ado.GetDataTable(_sysDataTableService
                    .QueryByClause(p => p.DataTableName.Equals("用户-lookupedit")).SQL),
                DisplayMember = "用户名称",
                ValueMember = "Id"
            };
            treeList1.Columns["UpdateUserId"].ColumnEdit = new RepositoryItemLookUpEdit()
            {
                Name = "repositoryItemLookUpEditUpdateUserId",
                DataSource = _sqlSugarClient.Ado.GetDataTable(_sysDataTableService
                    .QueryByClause(p => p.DataTableName.Equals("用户-lookupedit")).SQL),
                DisplayMember = "用户名称",
                ValueMember = "Id"
            };
        }

        public override void SetGridData()
        {
            treeList1.DataSource = _sysmenuService.Query().OrderBy(p=>p.OrderNo).ToList();
            treeList1.ExpandAll();
            treeList1.BestFitColumns();
        }

        public override void GridControlDoubleClickFunction()
        {
            ID = ((sysmenu)treeList1.GetFocusedRow()).Id;
        }

        /// <summary>
        /// 数据校验
        /// </summary>
        /// <returns></returns>
        private bool CheckData()
        {
            if (string.IsNullOrEmpty(PId.Text))
            {
                "父菜单不能为空".ShowTips();
                PId.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(MenuText.Text))
            {
                "菜单名称不能为空".ShowTips();
                MenuText.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(MenuCode.Text))
            {
                "菜单编码不能为空".ShowTips();
                MenuCode.Focus();
                return false;
            }

            if (IsExtendDevelop.Checked)
            {
                if (string.IsNullOrEmpty(MenuDll.Text))
                {
                    "菜单地址不能为空".ShowTips();
                    MenuDll.Focus();
                    return false;
                }
                if (string.IsNullOrEmpty(MenuName.Text))
                {
                    "菜单类名不能为空".ShowTips();
                    MenuName.Focus();
                    return false;
                }
            }
            if (MenuType.Text.Equals("Form"))
            {
                if (string.IsNullOrEmpty(MenuName.Text))
                {
                    "菜单类名不能为空".ShowTips();
                    MenuName.Focus();
                    return false;
                }
            }
            return true;
        }

        private void IsPublicFunction_CheckedChanged(object sender, EventArgs e)
        {
            if (IsPublicFunction.Checked)
            {
                BtnFunctionCreate btnFunctionCreate=new BtnFunctionCreate();
                memoEdit1.Text = btnFunctionCreate.Create(MenuText.Text, MenuCode.Text);
            }
        }

        public override void AddFunction()
        {
            CreateTime.DateTime=DateTime.Now;
            CreateUserId.EditValue = AppInfo.User.Id;
        }

        public override void EditFunction()
        {
            UpdateTime.DateTime = DateTime.Now;
            UpdateUserId.EditValue = AppInfo.User.Id;
        }

        public override bool SaveFunction()
        {
            var result = false;
            if (CheckData())
            {
                if (FormStatus == FormStatus.Add)
                {
                    ID = _sysmenuService.Insert(this.ControlDataToModel<sysmenu>());
                    result = ID > 0;
                }
                else
                {
                    result = _sysmenuService.UpdateN(this.ControlDataToModel<sysmenu>());
                }
            }
            PId.Properties.DataSource =
                _sqlSugarClient.Ado.GetDataTable(_sysDataTableService
                    .QueryByClause(p => p.DataTableName.Equals("菜单-treelistLookupedit")).SQL);
            return result;
        }

        public override bool DeleteFunction()
        {
            return _sysmenuService.DeleteN(new sysmenu(){Id = ID});
        }

        public override bool CancelFunction()
        {
            return base.CancelFunction();
        }

        public override void CloseFunction()
        {
            base.CloseFunction();
        }

        private void treeList1_DoubleClick(object sender, EventArgs e)
        {
            if (treeList1.GetFocusedRow()==null) return;
            xtraTabControl1.SelectedTabPage = xtraTabPage2;
            this.ModelDataToControl(treeList1.GetFocusedRow());
            FormStatus = FormStatus.View;
            InitToolBtnstatus();
            GridControlDoubleClickFunction();
        }

        private void simpleButton7_Click(object sender, EventArgs e)
        {
            string file = FileDialogHelper.Open("选择图标文件", FileDialogHelper.ImageFilter, "", Application.StartupPath + "Images");
            string result = "";
            if (!string.IsNullOrEmpty(file))
            {
                MenuIcon.Text = file.Replace(Application.StartupPath, "").Trim('\\');
            }
        }

        private void OrderNo_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void lblUpdateTime_Click(object sender, EventArgs e)
        {

        }

        private void UpdateTime_EditValueChanged(object sender, EventArgs e)
        {

        }
    }
}